//
//  NSMutableString+HACShield.m
//  HACShield
//
//  Created by Chengjie on 2019/5/22.
//

#import "NSMutableString+HACShield.h"
#import "NSObject+HACSwizzling.h"

@implementation NSMutableString (HACShield)

/**
 NSPlaceholderMutableString （alloc）
 __NSCFString
 */
+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 初始化 initWithString: stringWithString:
        hac_swizzleInstanceMethod(hac_getClass(@"NSP", @"laceholderMutableString"), @selector(initWithString:), @selector(hac_initWithString:));
        hac_swizzleInstanceMethod(hac_getClass(@"NSM", @"utableString"), @selector(replaceCharactersInRange:withString:), @selector(hac_replaceCharactersInRange:withString:));
        hac_swizzleInstanceMethod(hac_getClass(@"__NSCFS", @"tring"), @selector(insertString:atIndex:), @selector(hac_insertString:atIndex:));
        hac_swizzleInstanceMethod(hac_getClass(@"__NSCFS", @"tring"), @selector(deleteCharactersInRange:), @selector(hac_deleteCharactersInRange:));
        hac_swizzleInstanceMethod(hac_getClass(@"__NSCFS", @"tring"), @selector(appendString:), @selector(hac_appendString:));
        hac_swizzleInstanceMethod(hac_getClass(@"__NSCFS", @"tring"), @selector(setString:), @selector(hac_setString:));
    });
}

- (instancetype)hac_initWithString:(NSString *)aString {
    if (aString && [aString isKindOfClass:NSString.class]) {
        return [self hac_initWithString:aString];
    }
    return [self hac_initWithString:@""];
}

#pragma mark -其他公用方法

- (void)hac_replaceCharactersInRange:(NSRange)range withString:(NSString *)aString {
    if (aString && [aString isKindOfClass:NSString.class] && range.location >= 0 && range.length >= 0 && range.location + range.length <= self.length){
        [self hac_replaceCharactersInRange:range withString:aString];
    }
}

- (void)hac_insertString:(NSString *)aString atIndex:(NSUInteger)loc {
    if (aString && [aString isKindOfClass:NSString.class ] && loc >= 0 && loc <= self.length) {
        [self hac_insertString:aString atIndex:loc];
    }
}

- (void)hac_deleteCharactersInRange:(NSRange)range {
    if (range.location >=0 && range.length >=0 && range.location + range.length <= self.length){
        [self hac_deleteCharactersInRange:range];
    }
}

- (void)hac_appendString:(NSString *)aString {
    if (aString && [aString isKindOfClass:NSString.class]) {
        [self hac_appendString:aString];
    }
}

- (void)hac_setString:(NSString *)aString {
    if (aString && [aString isKindOfClass:NSString.class]) {
        [self hac_setString:aString];
    }
}
@end
